package net.j4love.protobuf.demo;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

import static net.j4love.protobuf.ProtobufCompilerUtils.generateJavaCode;
import static net.j4love.protobuf.LocalEnvConfiguration.*;


/**
 * @author he peng
 * @create 2018/5/11 15:48
 * @see
 */
public class ProtobufTest {

    @Test
    public void generateJavaCodeTest() throws Exception {

        // Compiling Your Protocol Buffers
        // protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto

        String catProtoFilePath = PROTO_PATH + "/cat.proto";
        String addressbookProtoFilePath = PROTO_PATH + "/addressbook.proto";
        generateJavaCode(PROTOBUF_COMPILER_ABSOLUTE_PATH , PROTO_PATH , CODE_PATH , catProtoFilePath , addressbookProtoFilePath);
    }


    @Test
    public void generateJavaClassTest() throws Exception {
        AddressBookProtos.AddressBook addressBook = AddressBookProtos.AddressBook.newBuilder().addPeople(AddressBookProtos.Person.newBuilder().setId(1).setName("James")).build();
        System.out.println(addressBook);
    }

    @Test
    public void serializeTest() throws Exception {
        CatProto.Cat cat = CatProto.Cat.newBuilder()
                    .setName("Tom")
                    .setColor("Blue")
                    .setId(666)
                    .build();
        System.out.println("Cat Protocol Buffers Serialized Size = " + cat.getSerializedSize());

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(cat);
        objectOutputStream.flush();
        System.out.println("Cat JDK Serialized Size = " + byteArrayOutputStream.size());
    }

    @Test
    public void parsingTest() throws Exception {
        CatProto.Cat cat = CatProto.Cat.newBuilder()
                .setName("Tom")
                .setColor("Blue")
                .setId(666)
                .build();
        System.out.println("source Cat : " + cat);
        byte[] serializedBytes = cat.toByteArray();
        CatProto.Cat parseCat = CatProto.Cat.parseFrom(serializedBytes);
        System.out.println("parse Cat : " + parseCat);
    }

    @Test
    public void anyFieldTest() throws Exception {
        String protobufFilePath = CODE_ABSOLUTE_PATH + "/src/main/java/net/j4love/protobuf/proto/zoo.proto";
        generateJavaCode(PROTOBUF_COMPILER_ABSOLUTE_PATH , PROTO_PATH , CODE_PATH , protobufFilePath);
        // TODO 没有正常生成类文件
    }


    @Test
    public void jsonTest() throws Exception {
        CatProto.Cat cat = CatProto.Cat.newBuilder()
                .setName("Tom")
                .setColor("Blue")
                .setId(666)
                .build();
    }

}
